#include "SimodoCommand.h"
#include "simodo/lsp-server/ServerContext.h"
#include "simodo/lsp-server/DocumentContext.h"

#include "simodo/variable/json/Rpc.h"
#include "simodo/variable/json/Serialization.h"
#include "simodo/inout/convert/functions.h"

namespace simodo::lsp
{

void SimodoCommand::work()
{
    if (_jsonrpc.is_valid()) {
        if (_jsonrpc.params().type() == variable::ValueType::Object) {

            std::shared_ptr<variable::Object> params_object = _jsonrpc.params().getObject();

            lsp::TextDocumentIdentifier doc_id;
            if (parseTextDocumentIdentifier(params_object->find(u"textDocument"), doc_id)) {
                DocumentContext * doc = _server.findDocument(doc_id.uri);
                if (doc) {
                    const variable::Value & command_value = params_object->find(u"command");
                    if (command_value.type() == variable::ValueType::String) {
                        variable::Value result = doc->produceSimodoCommandResponse(command_value.getString());
                        _server.sending().push(variable::JsonRpc(result, _jsonrpc.id()));
                        return;
                    }
                }
            }
        }
    }
    _server.log().error("There are wrong parameter structure of 'simodo/command' command", 
                        variable::toJson(_jsonrpc.value()));
    _server.sending().push(
        /// @todo Скорректировать коды (и тексты) ошибок
        variable::JsonRpc(-1,u"There are wrong parameter structure of 'simodo/command' command",
                            _jsonrpc.id()));
}

}